package com.yanghui.lingyue.utils.timeUtils

import java.util.*

object TimeUtils {

    fun getTimeDiff(start: Long, end: Long): String {
        val timeSpace: Long = end - start
        val day = timeSpace / 1000 / 3600 / 24
        val hour = timeSpace % (1000 * 3600 * 24) / (1000 * 3600)
        val minute = timeSpace % (1000 * 3600) / (1000 * 60)
        return "${day}天${hour}小时${minute}分钟"
    }

    fun checkAdult(birthday: String): Boolean {
        val birthdayYear = birthday.substring(0, 4).toInt()
        val birthdayMonth = birthday.substring(4, 6).toInt()
        val birthdayDay = birthday.substring(6, 8).toInt()
        val todayYear = Calendar.getInstance().get(Calendar.YEAR)
        val todayMonth = Calendar.getInstance().get(Calendar.MONTH) + 1
        val todayDay = Calendar.getInstance().get(Calendar.DATE)
        return if (todayYear - birthdayYear > 18) {
            true
        } else if (todayYear - birthdayYear < 18) {
            false
        } else {
            if (todayMonth - birthdayMonth > 0) {
                true
            } else if (todayMonth - birthdayMonth < 0) {
                false
            } else todayDay - birthdayDay >= 0
        }
    }

    fun getTodayString(): String {
        val todayYear = Calendar.getInstance().get(Calendar.YEAR)
        val todayMonth = Calendar.getInstance().get(Calendar.MONTH)
        val todayDay = Calendar.getInstance().get(Calendar.DATE)
        return String.format("%04d%02d%02d", todayYear, todayMonth, todayDay)
    }

    fun checkValidBirthday(birthday: String): Boolean {
        val dayArray = arrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
        if (birthday.length != 8)
            return false
        try {
            val birthdayYear = birthday.substring(0, 4).toInt()
            if (birthdayYear < 1000 || birthdayYear > 2100)
                return false
            if ((birthdayYear % 400 == 0) || (birthdayYear % 4 == 0 && birthdayYear % 100 != 0))
                dayArray[1] += 1
            val birthdayMonth = birthday.substring(4, 6).toInt()
            if (birthdayMonth < 1 || birthdayMonth > 12)
                return false
            val birthdayDay = birthday.substring(6, 8).toInt()
            if (birthdayDay < 1 || birthdayDay > dayArray[birthdayMonth - 1])
                return false
        } catch (e: Exception) {
            return false
        }
        return true
    }
}